package sdc.com.petscalendar.adapters;

import java.io.File;
import java.util.List;

import sdc.com.petscalendar.R;
import sdc.com.petscalendar.objects.Pet;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class PetAdapter extends ArrayAdapter<Pet> {
	private ItemClickListener itemClickListener;
	private ItemCalendarClickListener calendarClick;

	public PetAdapter(Context context, List<Pet> objects) {
		super(context, R.layout.layout_pet_item, objects);
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		View v = convertView;
		if (convertView == null) {
			v = ((LayoutInflater) getContext().getSystemService(
					Context.LAYOUT_INFLATER_SERVICE)).inflate(
					R.layout.layout_pet_item, parent, false);
			holder = new ViewHolder();
			holder.tvName = (TextView) v.findViewById(R.id.tv_pet_name);
			holder.ivAvatar = (ImageView) v.findViewById(R.id.iv_pet_avatar);
			holder.btnCalendar = (Button) v.findViewById(R.id.btn_pet_calendar);

			v.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		Pet pet = getItem(position);
		holder.tvName.setText(pet.getName());
		if (pet.getAvatar() != null && pet.getAvatar().length() > 0
				&& new File(pet.getAvatar()).exists()) {
			Bitmap bitmap = BitmapFactory.decodeFile(pet.getAvatar());
			holder.ivAvatar.setImageBitmap(bitmap);
		} else {
			holder.ivAvatar.setImageResource(R.drawable.pet_default_avatar);
		}

		holder.btnCalendar.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (calendarClick != null) {
					calendarClick.onItemCalendarClick(position);
				}
			}
		});
		v.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (itemClickListener != null) {
					itemClickListener.onItemClick(position);
				}
			}
		});

		return v;
	}

	public void setItemClickListener(ItemClickListener itemClickListener) {
		this.itemClickListener = itemClickListener;
	}

	public void setItemCalendarClick(ItemCalendarClickListener itemCalendarClick) {
		this.calendarClick = itemCalendarClick;
	}

	private class ViewHolder {
		private TextView tvName;
		private ImageView ivAvatar;
		private Button btnCalendar;
	}

	public interface ItemClickListener {
		public void onItemClick(int position);
	}

	public interface ItemCalendarClickListener {
		public void onItemCalendarClick(int position);
	}

}
